
package com.ys.chatserver.http.logic;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eva.epc.common.util.CommonUtils;
import com.eva.epc.common.util.RestHashMap;
import com.eva.framework.Processor;
import com.eva.framework.dbpool.DBShell;
import com.eva.framework.dto.SysActionConst;
import com.eva.framework.utils.EndsExceptionFactory;
import com.eva.framework.utils.LoggerFactory;
import com.google.gson.Gson;
import com.ys.chatserver.BaseConf;
import com.ys.chatserver.common.dto.cnst.RetResult;
import com.ys.chatserver.http.file.dto.BigFileType;
import com.ys.chatserver.http.file.u.BigFileUploder;
import com.ys.chatserver.http.file.u.ShortVideoUploader;
import com.ys.chatserver.http.logic.dto.JobDispatchConst;
import com.ys.chatserver.im.dto.PushResDTO;
import com.ys.chatserver.im.util.MessageHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 大文件信息相关的Http接口处理器实现类。
 *
 * @author Jack Jiang
 * @since 4.3
 */
public class FileInfoProcessor implements SysActionConst, Processor {
    public static DBShell db = new DBShell();

    /**
     * 处理器的核心实现方法.<br>
     * 可据job_dispatch_id找到对应的JobDispatcher，JobDispatcher又能据
     * action_id进行对应动作的处理，以完成本次操作请求.
     *
     * @param job_dispatch_id 作业调度ID
     * @param action_id       动作ID
     * @return 任意类型返回值
     */
    @Override
    public Object process(int job_dispatch_id, int action_id, Object _newData, Object _oldData, User user)
            throws Exception {
        Object ret = null;
        String newDataJSON = (String) _newData;

        if (job_dispatch_id == JobDispatchConst.LOGIC_FILE_MGR) {
            ret = maintainMgrFileJobDispatcher(action_id, newDataJSON, _oldData, user);
        } else {
            throw EndsExceptionFactory.INVALID_JOB_DISPATCHER_ID(job_dispatch_id);
        }
        return ret;
    }

    /**
     * 维护文件信息查询等请求.
     *
     * @param action_id 维护类型，SysConstant中的操作类型常量
     * @param newData   客端发送过来的本次修改新数据(可能为空，理论上与oldData不会同时空）
     * @param oldData   客端发送过来的本次修改前的老数据(可能为空，理论上与newData不会同时空）
     * @return 返回给客户端的对象
     */
    public String maintainMgrFileJobDispatcher(int action_id
            , Object newData, Object oldData, User user) throws Exception {
        JSONObject nwObj = JSONObject.parseObject((String) newData);
        if (action_id == ACTION_APPEND1) {

            String fileMd5 = nwObj.getString("file_md5").toLowerCase();
            String userUid = nwObj.getString("user_uid");
            String fileTypeStr = nwObj.getString("file_type");
            int fileType = BigFileType.FILE_TYPE_COMMON_BIG_FILE;
            if (!CommonUtils.isStringEmpty(fileTypeStr))
                fileType = CommonUtils.getIntValue(fileTypeStr, BigFileType.FILE_TYPE_COMMON_BIG_FILE);

            String retCode = "-1";
            int chunkCount = -1;

            if (!db.queryData("select 1 from chat_big_files where res_md5='" + fileMd5 + "' and file_status=0").isEmpty()) {
                retCode = "1";
            } else {
                File bigFileChunkSavedDir = null;
                if (fileType == BigFileType.FILE_TYPE_COMMON_BIG_FILE) {
                    bigFileChunkSavedDir = new File(BigFileUploder.getChunckCommonBigFileDir(fileMd5, userUid));
                } else if (fileType == BigFileType.FILE_TYPE_SHORT_VIDEO) {
                    bigFileChunkSavedDir = new File(ShortVideoUploader.getChunckShortVideoFileDir(fileMd5, userUid));
                }
                LoggerFactory.getLog().debug("[HTTP大文件信息查询] 要查询的文件分块临时目录："
                        + bigFileChunkSavedDir.getAbsolutePath());

                if (bigFileChunkSavedDir.exists()) {
                    chunkCount = bigFileChunkSavedDir.listFiles().length;
                    retCode = "2";
                } else {
                    retCode = "0";
                }
            }

            RestHashMap<String, Object> ret = RestHashMap.n().p("retCode", retCode).p("chunkCount", chunkCount + "");
            return JSON.toJSONString(ret);
        } else if (action_id == ACTION_DEVICE_GET_FILE_LIST) {
            String deviceUserId = nwObj.getString("devId");
            Integer pageSize = Integer.valueOf(nwObj.getString("pageSize"));
            Integer pageNumber = Integer.valueOf(nwObj.getString("pageNumber"));
            String keyword = nwObj.getString("keyword");
            //String message = RedisUtil.get(RtcRedisKeyConstants.DEV_FILE_LIST(deviceUserId));
            PushResDTO dto = new PushResDTO();
            dto.setPushId(user.getUserId());
            dto.setPageSize(pageSize);
            dto.setPageNumber(pageNumber);
            dto.setKeyword(keyword);
            MessageHelper.process89ACTION_DEVICE_UPLOAD_FILE_LIST(deviceUserId, new Gson().toJson(dto), null);
            return new Gson().toJson(RetResult.successResult("请求成功"));
        } else if (action_id == ACTION_REQUIRE_DEVICE_UPLOAD_FILE) {
            String deviceUserId = nwObj.getString("devId");
            JSONArray fileUrls = nwObj.getJSONArray("fileUrls");
            for (int i = 0; i < fileUrls.size(); i++) {
                MessageHelper.process90ACTION_DEVICE_FILE_UPLOAD(deviceUserId, fileUrls.get(i).toString(), null);
            }
            return new Gson().toJson(RetResult.successResult("请求成功!"));
        } else if (action_id == ACTION_QUERY_FILE_EXISTS) {
            JSONArray array = nwObj.getJSONArray("fileNames");
            List<JSONObject> json = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                String devId = jsonObject.getString("devId");
                String fileName = jsonObject.getString("fileName");
                String filePath = BaseConf.getInstance().getDIR_DEVICE_FILE_UPLOAD() + devId;
                JSONObject obj = new JSONObject();
                obj.put("devId", devId);
                obj.put("fileName", fileName);
                if (FileUtil.exist(filePath)) {
                    List<String> names = FileUtil.listFileNames(filePath);
                    boolean contains = names.contains(fileName);
                    obj.put("exist", contains);
                }else {
                    obj.put("exist",false);
                }
                json.add(obj);
            }
            return new Gson().toJson(RetResult.successResult("成功",json));
        } else if (action_id == ACTION_DEV_EXIST_FILE_QUERY) {
            String filePath = BaseConf.getInstance().getDIR_DEVICE_FILE_UPLOAD() + user.getUserId();
            if (FileUtil.exist(filePath)) {
                List<String> names = FileUtil.listFileNames(filePath);
                return new Gson().toJson(RetResult.successResult("成功",names));
            } else {
                return new Gson().toJson(RetResult.successResult("成功",new ArrayList<>()));
            }
        }
        throw EndsExceptionFactory.INVALID_ACTION_ID(action_id);
    }

}
